//
//  WTGiftService.m
//  WTLiveSDKDemo
//
//  Created by ben on 16/9/30.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTGiftService.h"

static NSString*  Cache_Key_WXGiftService = @"Cache_Key_WXGiftService";

@implementation WTGiftService

- (void)start:(NSDictionary*)param completionHandler:(WTServiceCompletionHandler)completionHandler{
    
    self.subPath = @"/live/gifts";
    self.param = param;
    
    id  cache = [[WTCacheManager shareManager] objectForKey:Cache_Key_WXGiftService];
    if(cache){
        NSArray* giftModels = [WTGiftModel mj_objectArrayWithKeyValuesArray:cache];
        completionHandler(giftModels,nil);
    }
    
    [HYBNetworking postWithUrl:self.subPath refreshCache:YES params:@{@"hash":[self encode]} success:^(id response) {
        
        NSInteger code = [response[@"code"] integerValue];
        if(code == 200){
            NSArray* giftModels = [WTGiftModel mj_objectArrayWithKeyValuesArray:response[@"hash"]];
            completionHandler(giftModels,nil);
            if(giftModels.count > 0){
                [[WTCacheManager shareManager] save:response[@"hash"] key:Cache_Key_WXGiftService];
            }
        }else {
            completionHandler(nil,nil);
        }
    } fail:^(NSError *error) {
        id  cache = [[WTCacheManager shareManager] objectForKey:Cache_Key_WXGiftService];
        if(cache){
            NSArray* giftModels = [WTGiftModel mj_objectArrayWithKeyValuesArray:cache];
            completionHandler(giftModels,nil);
        }else {
            completionHandler(nil,nil);
        }
    }];
}

@end
